// 主日学圣经问答 - 儿童版主应用程序

class KidsBibleQuizApp {
    constructor() {
        this.currentPage = 'welcomePage';
        this.audioEnabled = true;
        this.volume = 70; // 儿童版默认音量更高
        this.mascotMessages = [
            "你真棒！继续加油！🌟",
            "哇！你对圣经了解得真多！📚",
            "太厉害了！上帝一定很高兴！😊",
            "你是圣经小专家！👏",
            "继续学习，你会更棒的！💪"
        ];
        
        this.init();
    }

    // 初始化应用
    init() {
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => this.setupApp());
        } else {
            this.setupApp();
        }
    }

    // 设置应用
    setupApp() {
        this.loadSettings();
        this.bindEvents();
        this.updateWelcomeStats();
        this.initializeAudio();
        this.startBackgroundAnimations();

        // 强制默认关闭背景音乐并同步按钮图标
        if (window.mp3AudioSystem) {
            mp3AudioSystem.musicEnabled = false;
            mp3AudioSystem.stopBackgroundMusic();
        }
        const musicToggleBtn = document.getElementById('musicToggle');
        if (musicToggleBtn) {
            musicToggleBtn.textContent = '🔇';
            musicToggleBtn.title = '开启背景音乐';
        }
        
        console.log('🌈 主日学圣经问答游戏初始化完成！');
    }

    // 开始背景动画
    startBackgroundAnimations() {
        // 定期创建闪烁星星
        setInterval(() => {
            if (effectsSystem && Math.random() < 0.3) {
                effectsSystem.createTwinklingStars();
            }
        }, 5000);

        // 定期更新吉祥物消息
        setInterval(() => {
            this.updateMascotMessage();
        }, 10000);
    }

    // 更新吉祥物消息
    updateMascotMessage() {
        const speechBubble = document.querySelector('.speech-bubble p');
        if (speechBubble && this.currentPage === 'welcomePage') {
            const randomMessage = this.mascotMessages[Math.floor(Math.random() * this.mascotMessages.length)];
            speechBubble.textContent = randomMessage;
            
            // 添加动画效果
            speechBubble.parentElement.classList.add('animate-pulse');
            setTimeout(() => {
                speechBubble.parentElement.classList.remove('animate-pulse');
            }, 1000);
        }
    }

    // 加载设置
    loadSettings() {
        const settings = gameStorage.getSettings();
        this.audioEnabled = settings.soundEnabled;
        this.volume = settings.volume || 70;
        
        this.updateAudioControls();
        
        if (settings.largeFont) {
            document.body.classList.add('large-font');
        }
    }

    // 绑定事件
    bindEvents() {
        // 难度选择按钮
        document.querySelectorAll('.difficulty-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const difficulty = e.currentTarget.dataset.level;
                this.startGameWithAnimation(difficulty, e.currentTarget);
            });

            // 添加悬停效果
            btn.addEventListener('mouseenter', () => {
                this.playHoverSound();
                btn.classList.add('hover-glow');
            });

            btn.addEventListener('mouseleave', () => {
                btn.classList.remove('hover-glow');
            });
        });

        // 游戏控制按钮
        const quitBtn = document.getElementById('quitBtn');
        if (quitBtn) {
            quitBtn.addEventListener('click', () => this.quitGameWithAnimation());
        }

        // 结果页面按钮
        const shareBtn = document.getElementById('shareBtn');
        const playAgainBtn = document.getElementById('playAgainBtn');
        const backToMenuBtn = document.getElementById('backToMenuBtn');
        
        if (shareBtn) {
            shareBtn.addEventListener('click', (e) => this.showShareModalWithAnimation(e.currentTarget));
        }
        
        if (playAgainBtn) {
            playAgainBtn.addEventListener('click', (e) => this.playAgainWithAnimation(e.currentTarget));
        }
        
        if (backToMenuBtn) {
            backToMenuBtn.addEventListener('click', (e) => this.backToMenuWithAnimation(e.currentTarget));
        }

        // 成就相关按钮
        const achievementsBtn = document.getElementById('achievementsBtn');
        const backFromAchievements = document.getElementById('backFromAchievements');
        
        if (achievementsBtn) {
            achievementsBtn.addEventListener('click', (e) => this.showAchievementsWithAnimation(e.currentTarget));
        }
        
        if (backFromAchievements) {
            backFromAchievements.addEventListener('click', (e) => this.backToMenuWithAnimation(e.currentTarget));
        }

        // 音频控制
        const audioToggle = document.getElementById('audioToggle');
        const musicToggle = document.getElementById('musicToggle');
        const volumeSlider = document.getElementById('volumeSlider');
        
        if (audioToggle) {
            audioToggle.addEventListener('click', (e) => this.toggleAudioWithAnimation(e.currentTarget));
        }
        
        if (musicToggle) {
            musicToggle.addEventListener('click', (e) => this.toggleMusicWithAnimation(e.currentTarget));
        }
        
        if (volumeSlider) {
            volumeSlider.addEventListener('input', (e) => this.setVolume(e.target.value));
        }

        // 为所有按钮添加点击波纹效果
        document.addEventListener('click', (e) => {
            if (e.target.tagName === 'BUTTON' || e.target.closest('button')) {
                const button = e.target.tagName === 'BUTTON' ? e.target : e.target.closest('button');
                effectsSystem.createRipple(button, e);
                this.playClickSound();
            }
        });

        // 键盘事件
        document.addEventListener('keydown', (e) => this.handleKeyPress(e));

        // 页面可见性变化
        document.addEventListener('visibilitychange', () => this.handleVisibilityChange());

        // 窗口大小变化
        window.addEventListener('resize', () => this.handleResize());
    }

    // 带动画的开始游戏
    startGameWithAnimation(difficulty, button) {
        // 创建庆祝特效
        effectsSystem.celebrateSuccess(button);
        
        // 延迟启动游戏以显示动画
        setTimeout(() => {
            quizGame.startGame(difficulty);
            this.switchToPageWithAnimation('gamePage');
        }, 500);
    }

    // 自定义确认弹窗
    showConfirmDialog({ title = '确认操作', message = '确定吗？', confirmText = '确定', cancelText = '取消' } = {}) {
        return new Promise((resolve) => {
            const overlay = document.createElement('div');
            overlay.className = 'custom-confirm-overlay';
            overlay.innerHTML = `
                <div class="custom-confirm">
                    <div class="confirm-header">
                        <div class="confirm-title">${title}</div>
                        <button class="confirm-close" aria-label="关闭">×</button>
                    </div>
                    <div class="confirm-body">
                        <div class="confirm-mascot">🐑</div>
                        <div class="confirm-message">${message}</div>
                    </div>
                    <div class="confirm-actions">
                        <button class="btn-cancel">${cancelText}</button>
                        <button class="btn-confirm">${confirmText}</button>
                    </div>
                </div>
            `;
            Object.assign(overlay.style, {
                position: 'fixed',
                inset: '0',
                background: 'rgba(0,0,0,0.5)',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                zIndex: '10010',
                animation: 'fadeIn 0.2s ease-out'
            });
            const panel = overlay.querySelector('.custom-confirm');
            Object.assign(panel.style, {
                width: 'min(90vw, 420px)',
                background: 'linear-gradient(135deg, #ffffff, #f7f2ff)',
                borderRadius: '20px',
                boxShadow: '0 12px 40px rgba(0,0,0,0.25)',
                overflow: 'hidden',
                transform: 'translateY(10px)',
                opacity: '0',
                transition: 'all 180ms ease'
            });
            const header = overlay.querySelector('.confirm-header');
            Object.assign(header.style, {
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
                padding: '14px 16px',
                background: 'linear-gradient(135deg, #667eea, #764ba2)',
                color: '#fff'
            });
            const titleEl = overlay.querySelector('.confirm-title');
            Object.assign(titleEl.style, {
                fontWeight: '700',
                fontSize: '1.05rem'
            });
            const closeBtn = overlay.querySelector('.confirm-close');
            Object.assign(closeBtn.style, {
                background: 'transparent',
                border: 'none',
                color: '#fff',
                fontSize: '1.4rem',
                cursor: 'pointer'
            });
            const body = overlay.querySelector('.confirm-body');
            Object.assign(body.style, {
                padding: '18px 18px 6px',
                display: 'flex',
                alignItems: 'center',
                gap: '12px'
            });
            const mascot = overlay.querySelector('.confirm-mascot');
            Object.assign(mascot.style, {
                fontSize: '2rem',
                filter: 'drop-shadow(0 2px 6px rgba(0,0,0,0.15))'
            });
            const msg = overlay.querySelector('.confirm-message');
            Object.assign(msg.style, {
                fontSize: '1rem',
                color: '#333',
                lineHeight: '1.5'
            });
            const actions = overlay.querySelector('.confirm-actions');
            Object.assign(actions.style, {
                padding: '14px 16px 18px',
                display: 'flex',
                justifyContent: 'flex-end',
                gap: '10px'
            });
            const btnCancel = overlay.querySelector('.btn-cancel');
            const btnConfirm = overlay.querySelector('.btn-confirm');
            const baseBtn = {
                border: 'none',
                padding: '10px 16px',
                borderRadius: '999px',
                fontSize: '0.95rem',
                cursor: 'pointer',
                transition: 'transform 120ms ease, box-shadow 120ms ease'
            };
            Object.assign(btnCancel.style, {
                ...baseBtn,
                background: '#eceff1',
                color: '#455a64',
                boxShadow: '0 2px 8px rgba(0,0,0,0.08)'
            });
            Object.assign(btnConfirm.style, {
                ...baseBtn,
                background: 'linear-gradient(135deg, #4caf50, #66bb6a)',
                color: '#fff',
                boxShadow: '0 3px 10px rgba(76,175,80,0.35)'
            });
            const hoverUp = (el) => {
                el.addEventListener('mouseenter', () => el.style.transform = 'translateY(-1px)');
                el.addEventListener('mouseleave', () => el.style.transform = 'translateY(0)');
            };
            hoverUp(btnCancel);
            hoverUp(btnConfirm);

            document.body.appendChild(overlay);
            requestAnimationFrame(() => {
                panel.style.transform = 'translateY(0)';
                panel.style.opacity = '1';
            });

            const cleanup = (confirmed, immediate = false) => {
                if (immediate) {
                    overlay.remove();
                    resolve(confirmed);
                    return;
                }
                panel.style.transform = 'translateY(10px)';
                panel.style.opacity = '0';
                overlay.style.animation = 'fadeOut 0.18s ease-in';
                setTimeout(() => {
                    overlay.remove();
                    resolve(confirmed);
                }, 160);
            };

            closeBtn.addEventListener('click', () => cleanup(false));
            btnCancel.addEventListener('click', () => cleanup(false));
            btnConfirm.addEventListener('click', () => cleanup(true, true));
            overlay.addEventListener('click', (e) => {
                if (e.target === overlay) cleanup(false);
            });
            document.addEventListener('keydown', function onKey(e) {
                if (e.key === 'Escape') {
                    document.removeEventListener('keydown', onKey);
                    cleanup(false);
                }
            });
        });
    }

    // 带动画的退出游戏（使用自定义弹窗）
    quitGameWithAnimation() {
        this.showConfirmDialog({
            title: '🐑 小羊咩咩问',
            message: '真的要退出游戏吗？你的进度会被保存哦！',
            confirmText: '确认退出',
            cancelText: '继续挑战'
        }).then((confirmed) => {
            if (!confirmed) return;
            // 直接回主菜单，不保留任何弹窗过渡
            try { quizGame.quitGame(); } catch(e) {}
            this.switchToPageWithAnimation('welcomePage');
            this.updateWelcomeStats();
        });
    }

    // 带动画的显示分享弹窗
    showShareModalWithAnimation(button) {
        effectsSystem.celebrateSuccess(button);
        setTimeout(() => {
            // 获取游戏统计数据
            const gameStats = window.scoringSystem ? 
                window.scoringSystem.getGameStats() : 
                {
                    finalScore: 0,
                    accuracy: 0,
                    maxStreak: 0,
                    timeTaken: 0,
                    correctAnswers: 0,
                    totalQuestions: 0
                };
            
            console.log('📤 显示分享弹窗，游戏统计:', gameStats);
            
            if (window.shareSystem) {
                window.shareSystem.showShareModal(gameStats);
            } else {
                console.error('❌ shareSystem未定义');
                alert('分享功能暂时不可用，请稍后再试。');
            }
        }, 300);
    }

    // 带动画的再玩一次
    playAgainWithAnimation(button) {
        effectsSystem.celebrateSuccess(button);
        setTimeout(() => {
            quizGame.restartGame();
            this.switchToPageWithAnimation('gamePage');
        }, 500);
    }

    // 带动画的返回主菜单
    backToMenuWithAnimation(button) {
        effectsSystem.celebrateSuccess(button);
        setTimeout(() => {
            this.switchToPageWithAnimation('welcomePage');
            this.updateWelcomeStats();
        }, 300);
    }

    // 带动画的显示成就
    showAchievementsWithAnimation(button) {
        effectsSystem.celebrateSuccess(button);
        
        // 检查是否有徽章（从存储中过滤已解锁）
        let unlockedAchievements = [];
        try {
            const all = window.gameStorage ? window.gameStorage.getAchievements() : {};
            unlockedAchievements = Object.values(all).filter(a => a && a.unlocked);
        } catch (e) {
            console.warn('读取成就数据失败，回退为空列表', e);
            unlockedAchievements = [];
        }
        
        if (unlockedAchievements.length === 0) {
            // 显示友好提示
            this.showFriendlyAchievementMessage();
            return;
        }
        
        setTimeout(() => {
            quizGame.showAchievements();
        }, 300);
    }

    // 显示友好的徽章提示
    showFriendlyAchievementMessage() {
        const messages = [
            "🌟 还没有徽章？没关系！",
            "🎮 开始游戏就能获得第一个徽章哦！",
            "💪 每答对一题都是进步！",
            "🏆 徽章在等着你来收集！",
            "😊 加油，小朋友！"
        ];
        
        // 创建临时提示框
        const messageDiv = document.createElement('div');
        messageDiv.className = 'friendly-message';
        messageDiv.innerHTML = `
            <div class="message-content">
                <div class="message-icon">🎈</div>
                <h3>还没有徽章呢！</h3>
                <p>开始游戏答题就能获得你的第一个徽章啦！</p>
                <p>每个徽章都代表你的进步哦！💖</p>
                <button class="friendly-btn" onclick="this.parentElement.parentElement.remove()">我知道了！</button>
            </div>
        `;
        
        document.body.appendChild(messageDiv);
        
        // 添加样式
        if (!document.getElementById('friendlyMessageStyle')) {
            const style = document.createElement('style');
            style.id = 'friendlyMessageStyle';
            style.textContent = `
                .friendly-message {
                    position: fixed;
                    top: 0;
                    left: 0;
                    width: 100%;
                    height: 100%;
                    background: rgba(0, 0, 0, 0.5);
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    z-index: 10000;
                    animation: fadeIn 0.3s ease;
                }
                
                .message-content {
                    background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 50%, #fecfef 100%);
                    padding: 30px;
                    border-radius: 20px;
                    text-align: center;
                    max-width: 400px;
                    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
                    animation: bounceIn 0.5s ease;
                }
                
                .message-icon {
                    font-size: 3rem;
                    margin-bottom: 15px;
                }
                
                .message-content h3 {
                    color: #333;
                    margin-bottom: 15px;
                    font-size: 1.5rem;
                }
                
                .message-content p {
                    color: #555;
                    margin-bottom: 10px;
                    font-size: 1.1rem;
                }
                
                .friendly-btn {
                    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                    color: white;
                    border: none;
                    padding: 12px 24px;
                    border-radius: 25px;
                    font-size: 1.1rem;
                    cursor: pointer;
                    margin-top: 15px;
                    transition: transform 0.2s ease;
                }
                
                .friendly-btn:hover {
                    transform: scale(1.05);
                }
                
                @keyframes bounceIn {
                    0% { transform: scale(0.3); opacity: 0; }
                    50% { transform: scale(1.05); }
                    70% { transform: scale(0.9); }
                    100% { transform: scale(1); opacity: 1; }
                }
            `;
            document.head.appendChild(style);
        }
        
        // 3秒后自动关闭
        setTimeout(() => {
            if (messageDiv.parentElement) {
                messageDiv.remove();
            }
        }, 5000);
    }

    // 带动画的音频切换
    toggleAudioWithAnimation(button) {
        this.audioEnabled = !this.audioEnabled;
        this.saveAudioSettings();
        this.updateAudioControls();
        
        if (window.mp3AudioSystem) {
            mp3AudioSystem.setEnabled(this.audioEnabled);
        }
        
        // 创建特效
        if (this.audioEnabled) {
            effectsSystem.createParticles(
                button.getBoundingClientRect().left + button.offsetWidth / 2,
                button.getBoundingClientRect().top + button.offsetHeight / 2,
                8, 'sparkle'
            );
            this.playClickSound();
        } else {
            button.classList.add('animate-wiggle');
            setTimeout(() => button.classList.remove('animate-wiggle'), 1000);
        }
    }

    // 带动画的背景音乐切换
    toggleMusicWithAnimation(button) {
        if (window.mp3AudioSystem) {
            const musicEnabled = mp3AudioSystem.toggleBackgroundMusic();
            
            // 更新按钮显示
            button.textContent = musicEnabled ? '🎵' : '🔇';
            button.title = musicEnabled ? '关闭背景音乐' : '开启背景音乐';
            
            // 创建特效
            if (musicEnabled) {
                effectsSystem.createParticles(
                    button.getBoundingClientRect().left + button.offsetWidth / 2,
                    button.getBoundingClientRect().top + button.offsetHeight / 2,
                    12, 'music'
                );
                this.playClickSound();
            } else {
                button.classList.add('animate-wiggle');
                setTimeout(() => button.classList.remove('animate-wiggle'), 1000);
            }
        }
    }

    // 带动画的页面切换
    switchToPageWithAnimation(pageId) {
        const currentPageElement = document.querySelector('.page.active');
        const targetPageElement = document.getElementById(pageId);
        
        if (currentPageElement) {
            currentPageElement.classList.add('animate-slideOutLeft');
            setTimeout(() => {
                currentPageElement.classList.remove('active', 'animate-slideOutLeft');
            }, 300);
        }
        
        setTimeout(() => {
            if (targetPageElement) {
                targetPageElement.classList.add('active', 'animate-slideInRight');
                this.currentPage = pageId;
                
                setTimeout(() => {
                    targetPageElement.classList.remove('animate-slideInRight');
                }, 500);
            }
        }, 150);
    }

    // 切换页面（原方法保留兼容性）
    switchToPage(pageId) {
        this.switchToPageWithAnimation(pageId);
    }

    // 更新欢迎页面统计
    updateWelcomeStats() {
        const stats = gameStorage.getUserStats();
        const totalQuestions = document.getElementById('totalQuestions');
        const totalBadges = document.getElementById('totalBadges');
        
        if (totalQuestions) {
            effectsSystem.animateNumber(totalQuestions, totalQuestions.textContent, stats.totalQuestions);
        }
        if (totalBadges) {
            effectsSystem.animateNumber(totalBadges, totalBadges.textContent, stats.totalBadges);
        }
    }

    // 初始化音频
    initializeAudio() {
        if (window.mp3AudioSystem) {
            mp3AudioSystem.setVolume(this.volume / 100);
            mp3AudioSystem.setEnabled(this.audioEnabled);
            mp3AudioSystem.preloadSounds();
            
            // 启动背景音乐（延迟启动以确保用户交互）
            setTimeout(() => {
                if (this.audioEnabled) {
                    mp3AudioSystem.playBackgroundMusic();
                }
            }, 1000);
        }
    }

    // 更新音频控制UI
    updateAudioControls() {
        const audioToggle = document.getElementById('audioToggle');
        const volumeSlider = document.getElementById('volumeSlider');
        
        if (audioToggle) {
            audioToggle.textContent = this.audioEnabled ? '🔊' : '🔇';
            audioToggle.title = this.audioEnabled ? '关闭音效' : '开启音效';
            
            // 添加动画效果
            audioToggle.classList.add('animate-bounce');
            setTimeout(() => audioToggle.classList.remove('animate-bounce'), 1000);
        }
        
        if (volumeSlider) {
            volumeSlider.value = this.volume;
            volumeSlider.disabled = !this.audioEnabled;
        }
    }

    // 设置音量
    setVolume(volume) {
        this.volume = parseInt(volume);
        this.saveAudioSettings();
        
        if (window.mp3AudioSystem) {
            mp3AudioSystem.setVolume(this.volume / 100);
        }
    }

    // 保存音频设置
    saveAudioSettings() {
        gameStorage.updateSettings({
            soundEnabled: this.audioEnabled,
            volume: this.volume
        });
    }

    // 播放点击音效
    playClickSound() {
        if (this.audioEnabled && window.mp3AudioSystem) {
            mp3AudioSystem.setVolume(this.volume / 100);
            mp3AudioSystem.setEnabled(this.audioEnabled);
            mp3AudioSystem.playSound('click');
        }
    }

    // 播放悬停音效
    playHoverSound() {
        if (this.audioEnabled && window.mp3AudioSystem) {
            // 使用较低音量的点击音效作为悬停音效
            const originalVolume = this.volume;
            mp3AudioSystem.setVolume((this.volume * 0.3) / 100);
            mp3AudioSystem.playSound('click');
            mp3AudioSystem.setVolume(originalVolume / 100);
        }
    }

    // 处理键盘按键
    handleKeyPress(e) {
        if (e.key === 'Escape') {
            if (this.currentPage === 'gamePage') {
                this.quitGameWithAnimation();
            } else if (this.currentPage !== 'welcomePage') {
                this.backToMenuWithAnimation();
            }
        }
        
        if (this.currentPage === 'gamePage' && quizGame.gameActive) {
            const num = parseInt(e.key);
            if (num >= 1 && num <= 4) {
                const optionBtns = document.querySelectorAll('.option-btn');
                if (optionBtns[num - 1] && !optionBtns[num - 1].disabled) {
                    // 创建键盘选择特效
                    effectsSystem.celebrateSuccess(optionBtns[num - 1]);
                    setTimeout(() => optionBtns[num - 1].click(), 200);
                }
            }
        }
        
        if (e.key === ' ' || e.key === 'Enter') {
            const nextBtn = document.getElementById('nextBtn');
            if (nextBtn && nextBtn.style.display !== 'none') {
                e.preventDefault();
                effectsSystem.celebrateSuccess(nextBtn);
                setTimeout(() => nextBtn.click(), 200);
            }
        }
    }

    // 处理页面可见性变化
    handleVisibilityChange() {
        if (document.hidden) {
            if (quizGame && quizGame.gameActive) {
                quizGame.pauseGame();
            }
        } else {
            if (quizGame && quizGame.gameActive) {
                quizGame.resumeGame();
            }
        }
    }

    // 处理窗口大小变化
    handleResize() {
        // 清除可能超出屏幕的特效
        if (effectsSystem) {
            effectsSystem.clearAllEffects();
        }
    }

    // 显示鼓励消息
    showEncouragement(message, type = 'success') {
        const encouragement = document.createElement('div');
        encouragement.className = `encouragement-message ${type}`;
        encouragement.innerHTML = `
            <div class="encouragement-icon">${type === 'success' ? '🌟' : '💪'}</div>
            <div class="encouragement-text">${message}</div>
        `;
        
        Object.assign(encouragement.style, {
            position: 'fixed',
            top: '50%',
            left: '50%',
            transform: 'translate(-50%, -50%)',
            background: type === 'success' ? 'linear-gradient(135deg, #4caf50, #66bb6a)' : 'linear-gradient(135deg, #ff9800, #ffb74d)',
            color: 'white',
            padding: '20px 30px',
            borderRadius: '20px',
            fontSize: '1.2rem',
            fontWeight: 'bold',
            textAlign: 'center',
            boxShadow: '0 8px 30px rgba(0,0,0,0.3)',
            zIndex: '10001',
            animation: 'bounceIn 0.8s ease-out'
        });
        
        document.body.appendChild(encouragement);
        
        // 创建庆祝特效
        setTimeout(() => {
            const rect = encouragement.getBoundingClientRect();
            effectsSystem.createFireworks(
                rect.left + rect.width / 2,
                rect.top + rect.height / 2
            );
        }, 400);
        
        // 自动移除
        setTimeout(() => {
            encouragement.style.animation = 'fadeOut 0.5s ease-in forwards';
            setTimeout(() => {
                if (encouragement.parentNode) {
                    encouragement.parentNode.removeChild(encouragement);
                }
            }, 500);
        }, 3000);
    }

    // 显示成就解锁动画
    showAchievementUnlock(achievement) {
        const modal = document.createElement('div');
        modal.className = 'achievement-unlock-modal';
        modal.innerHTML = `
            <div class="achievement-unlock-content">
                <div class="achievement-unlock-header">
                    <h2>🎉 恭喜你！</h2>
                    <p>获得新徽章！</p>
                </div>
                <div class="achievement-unlock-badge">
                    <div class="badge-icon">${achievement.icon}</div>
                    <div class="badge-name">${achievement.name}</div>
                    <div class="badge-description">${achievement.description}</div>
                </div>
                <button class="achievement-close-btn" onclick="this.parentElement.parentElement.remove()">
                    太棒了！ ✨
                </button>
            </div>
        `;
        
        Object.assign(modal.style, {
            position: 'fixed',
            top: '0',
            left: '0',
            width: '100%',
            height: '100%',
            background: 'rgba(0,0,0,0.8)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            zIndex: '10002',
            animation: 'fadeIn 0.5s ease-out'
        });
        
        document.body.appendChild(modal);
        
        // 创建庆祝特效
        setTimeout(() => {
            effectsSystem.gameCompleteCelebration();
        }, 500);
        
        // 不再播放成就音效（已移除）
        if (this.audioEnabled && window.mp3AudioSystem) {
            mp3AudioSystem.playSound('achievement');
        }
    }

    // 创建学习提示
    showLearningTip(tip) {
        const tipElement = document.createElement('div');
        tipElement.className = 'learning-tip';
        tipElement.innerHTML = `
            <div class="tip-mascot">🐑</div>
            <div class="tip-content">
                <h4>小羊咩咩说：</h4>
                <p>${tip}</p>
            </div>
        `;
        
        Object.assign(tipElement.style, {
            position: 'fixed',
            bottom: '20px',
            right: '20px',
            background: 'linear-gradient(135deg, #e3f2fd, #f3e5f5)',
            border: '3px solid #42a5f5',
            borderRadius: '20px',
            padding: '15px',
            maxWidth: '300px',
            boxShadow: '0 8px 30px rgba(0,0,0,0.2)',
            zIndex: '10000',
            animation: 'slideInRight 0.5s ease-out'
        });
        
        document.body.appendChild(tipElement);
        
        // 自动移除
        setTimeout(() => {
            tipElement.style.animation = 'slideOutRight 0.5s ease-in forwards';
            setTimeout(() => {
                if (tipElement.parentNode) {
                    tipElement.parentNode.removeChild(tipElement);
                }
            }, 500);
        }, 5000);
    }

    // 获取应用状态
    getAppState() {
        return {
            currentPage: this.currentPage,
            audioEnabled: this.audioEnabled,
            volume: this.volume,
            gameState: quizGame ? quizGame.getGameState() : null,
            userStats: gameStorage.getUserStats()
        };
    }
}

// 添加额外的CSS动画
const additionalCSS = `
@keyframes slideOutLeft {
    from {
        transform: translateX(0);
        opacity: 1;
    }
    to {
        transform: translateX(-100%);
        opacity: 0;
    }
}

@keyframes slideInRight {
    from {
        transform: translateX(100%);
        opacity: 0;
    }
    to {
        transform: translateX(0);
        opacity: 1;
    }
}

@keyframes slideOutRight {
    from {
        transform: translateX(0);
        opacity: 1;
    }
    to {
        transform: translateX(100%);
        opacity: 0;
    }
}

.achievement-unlock-content {
    background: linear-gradient(135deg, #fff3e0, #f3e5f5);
    border-radius: 30px;
    padding: 40px;
    text-align: center;
    max-width: 400px;
    animation: bounceIn 0.8s ease-out;
}

.achievement-unlock-header h2 {
    font-size: 2rem;
    margin-bottom: 10px;
    background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
}

.achievement-unlock-badge {
    margin: 30px 0;
}

.badge-icon {
    font-size: 4rem;
    margin-bottom: 15px;
    animation: bounce 1s ease-in-out infinite;
}

.badge-name {
    font-size: 1.5rem;
    font-weight: bold;
    color: #2c3e50;
    margin-bottom: 10px;
}

.badge-description {
    color: #546e7a;
    font-size: 1rem;
}

.achievement-close-btn {
    background: linear-gradient(135deg, #4caf50, #66bb6a);
    color: white;
    border: none;
    padding: 15px 30px;
    border-radius: 25px;
    font-size: 1.1rem;
    font-weight: bold;
    cursor: pointer;
    transition: all 0.3s ease;
}

.achievement-close-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 20px rgba(76, 175, 80, 0.4);
}

.learning-tip {
    display: flex;
    align-items: center;
    gap: 15px;
}

.tip-mascot {
    font-size: 2rem;
    animation: bounce 2s ease-in-out infinite;
}

.tip-content h4 {
    margin: 0 0 8px 0;
    color: #2c3e50;
    font-size: 1rem;
}

.tip-content p {
    margin: 0;
    color: #546e7a;
    font-size: 0.9rem;
    line-height: 1.4;
}
`;

// 注入额外CSS
const additionalStyle = document.createElement('style');
additionalStyle.textContent = additionalCSS;
document.head.appendChild(additionalStyle);

// 页面加载完成后初始化应用
window.addEventListener('load', () => {
    window.kidsBibleQuizApp = new KidsBibleQuizApp();
});

// 处理页面卸载
window.addEventListener('beforeunload', (e) => {
    if (quizGame && quizGame.gameActive) {
        e.preventDefault();
        e.returnValue = '🐑 游戏正在进行中，小羊咩咩会想念你的！确定要离开吗？';
    }
});

// 处理错误
window.addEventListener('error', (e) => {
    console.error('应用错误:', e.error);
    if (window.kidsBibleQuizApp) {
        kidsBibleQuizApp.showEncouragement('哎呀，出现了小问题！请刷新页面重试 🔄', 'error');
    }
});

// 处理未捕获的Promise错误
window.addEventListener('unhandledrejection', (e) => {
    console.error('未处理的Promise错误:', e.reason);
    if (window.kidsBibleQuizApp) {
        kidsBibleQuizApp.showEncouragement('网络小精灵在打瞌睡，请检查网络连接 📡', 'error');
    }
});